<?php


namespace app\sports\tlive\service;

use think\Exception;
use app\common\HTTP;
use think\facade\Log;
use app\sports\tlive\model\LineupModel;
use app\common\InstanceTrait;
class TliveCaiji
{
    private $user = '';
    private  $secret ='';
//    接口名:足球实时统计
//    接口频次:2/s
    private $url = 'open.sportnanoapi.com/api/sports/football/match/detail_live';

    protected function __construct()
    {
        $this->user = Env::get('nami.user');
        $this->secret = Env::get('nami.secret');
    }
    /*
     * 采集数据
     */
    public function Execs()
    {
        try {
            $tliveressult = json_decode(HTTP::getInstance()->doGet($this->url."?user=$this->user&secret=$this->secret"), true);
//        查询最后一次发生的事件
//        思路:
//        开启异常
//        先获取远程的数据
//        根据返回的数据,循环遍历的查询,本地的最后一次发生的事件时间time的字段,纳米id
            $tlivearray=[];
            foreach ($tliveressult as $value){
                // 查询数据库,查询数据库纳米id中与这个返回匹配的记录的记录
                $last = LineupModel::getInstance()->Lasttime($value['id']);
                // 如果事件时间大于我查出的,就组装数据,追加到一个数组中,最后直接批量插入数据
                if ($value['time']>$last['time']){
                   $tlivearray[]=[
                       'nami_match_id' =>$value['id'],
                       'main'         =>$value['tlive']['main'],
                       'data'         =>$value['tlive']['data'],
                       'position'     =>$value['tlive']['position'],
                       'incidents'    =>$value['incidents'],
                       'type'         =>$value['tlive']['type'],
                       'time'         =>$value['tlive']['time'],
                       'create_time'  =>date('Y-m-d H:i:s',time()),
                       'update_time'  =>date('Y-m-d H:i:s',time()),
                   ];
                }
            }
//            如果数组有数据才批量插入数据
            if (isset($tlivearray) && (!empty($tlivearray))) {
                $tliveresult=LineupModel::getInstance()->InsertTliveAll($tlivearray);
            }
            Log::log('info','文字直播采集完成');
        }catch(Exception $e){
            Log::error('文字直播错误:'.$e->getMessage());
            return [];
        }


    }
}